using System;
using System.Configuration;
using System.Reflection;

namespace Tino.Core.Utility
{
    public class ConfigManager
    {
        ExeConfigurationFileMap fileMap;
        string configFullPath;
        Configuration cfg;

        public string ConfigurationFilePath
        {
            get { return configFullPath; }
        }

        public ConfigManager()
        {
            configFullPath = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            configFullPath += string.Format(@"\{0}\{0}.exe.config", Assembly.GetEntryAssembly().GetName().Name);

            fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configFullPath;

            cfg = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
        }

        public object GetValue(string Key, Type type, object defaultValue)
        {
            lock (this)
            {
                if (cfg.AppSettings.Settings[Key] == null)
                    return defaultValue;

                string ret = cfg.AppSettings.Settings[Key].Value;
                return Convert.ChangeType(ret, type);
            }
        }

        public void SetValue(string Key, object Value)
        {
            lock (this)
            {
                if (cfg.AppSettings.Settings[Key] != null)
                    cfg.AppSettings.Settings.Remove(Key);

                cfg.AppSettings.Settings.Add(Key, Value.ToString());
                cfg.Save();
            }
        }
    }
}